﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.IO;
using System.Globalization;

namespace Goldlight.Mvvm.Base.Infrastructure.Skins
{
    /// <summary>
    /// This class will be responsible for loading skins to be used in Goldlight applications.
    /// </summary>
    /// <remarks>
    /// As well as loading skins manually, localised skins will be detected by this class and 
    /// picked up.
    /// </remarks>
    public class SkinManager
    {
        private List<Skin> _skins = new List<Skin>();
        /// <summary>
        /// Initialize a new instance of <see cref="SkinManager"/>.
        /// </summary>
        public SkinManager()
        {
        }

        /// <summary>
        /// Goldlight expects to find skins in a sub-directory called Skins. Local themse are stored in appropriately named
        /// subdirectories.
        /// </summary>
        public void LoadLocalisedSkins()
        {
            string directory = FindLocalisedDirectory("Skins", CultureInfo.CurrentUICulture.NativeName);
            if (string.IsNullOrEmpty(directory))
            {
                directory = FindLocalisedDirectory("Skins", CultureInfo.CurrentUICulture.TwoLetterISOLanguageName);
            }
            if (!string.IsNullOrEmpty(directory))
            {
                // Now, look for the files in the directory that actually contain this format.
                DirectoryInfo directoryInfo = new DirectoryInfo(directory);
                FileInfo[] files = directoryInfo.GetFiles("*.dll", SearchOption.AllDirectories);
                foreach (FileInfo file in files)
                {
                    AddSkin(Path.GetFileNameWithoutExtension(file.Name), file.FullName);
                }
            }
        }

        private string FindLocalisedDirectory(string subDirectory, string localFormat)
        {
            string directory = Path.Combine(NativeMethods.StartupPath(), subDirectory);
            directory = Path.Combine(directory, localFormat);
            if (Directory.Exists(directory))
            {
                return directory;
            }
            return string.Empty;
        }

        public void AddSkin(string skinName, string assemblyPath)
        {
            _skins.Add(new AppDomainAssemblySkin(skinName, assemblyPath));
        }
    }
}
